﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Regions;
using System.Windows;

namespace Infrastructure.WpfClient.Composite.Regions.LateralRegion
{
    public class LateralViewRegion : Region
    {
        public LateralViewRegion(IEventAggregator eventAggregator)
        {
            eventAggregator.GetEvent<GlobalEvents.CloseViewEvent>().Subscribe(Remove);
        }
        public override Microsoft.Practices.Composite.Regions.IRegionManager Add(object view, string viewName, bool createRegionManagerScope)
        {            
            IRegionManager manager = createRegionManagerScope ? this.RegionManager.CreateRegionManager() : this.RegionManager;
            this.InnerAdd(view, viewName, manager);
            return manager;
        }
        private void InnerAdd(object view, string viewName, IRegionManager scopedRegionManager)
        {
            if (this.ItemMetadataCollection.FirstOrDefault(x => x.Item == view) != null)
            {
                throw new InvalidOperationException("RegionViewExistsException");
            }
            ItemMetadata itemMetadata = new ItemMetadata(view);
            if (!string.IsNullOrEmpty(viewName))
            {
                if (this.ItemMetadataCollection.FirstOrDefault(x => x.Name == viewName) != null)
                {
                    throw new InvalidOperationException("RegionViewNameExistsException " + viewName);
                }
                itemMetadata.Name = viewName;
            }
            DependencyObject dependencyObject = view as DependencyObject;

            if (dependencyObject != null)
            {
                Microsoft.Practices.Composite.Presentation.Regions.RegionManager.SetRegionManager(dependencyObject, scopedRegionManager);
            }
            this.ItemMetadataCollection.Add(itemMetadata);
        }
        public override void Remove(object view)
        {
            var query = (from c in this.Views where c == view select c).SingleOrDefault();
            if (query != null)
            {
                if (query is IDisposable) ((IDisposable)query).Dispose();
                base.Remove(view);
            }
        }
        public override void Activate(object view)
        {
            var query = (from c in this.Views where c == view select c).SingleOrDefault();
            if (query != null)
                base.Activate(view);
        }
        public override void Deactivate(object view)
        {
            var query = (from c in this.Views where c == view select c).SingleOrDefault();
            if (query != null)
                base.Deactivate(view);
        }
    }
}
